package org.toycode.logindemo.application.util;

/**
 * This class depicts a time out timer.
 *
 * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
 * @version 1.0.0.0, Aug 19, 2009
 */
public class TimeOutThread extends Thread {

    private long timeout;
    private boolean isCanceled = false;
    private RuntimeException timeoutException;

    public TimeOutThread(final long timeout,
                         final RuntimeException timeoutErr) {
        this.timeout = timeout;
        this.timeoutException = timeoutErr;
        this.setDaemon(true);
    }

    public synchronized void cancel() {
        isCanceled = true;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(timeout);
            if (!isCanceled) {
                throw timeoutException;
            }
        } catch (final InterruptedException e) {
            e.printStackTrace();
        }
    }
}
